/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package java.io;

import com.google.j2objc.LibraryNotLinkedError;
import java.lang.reflect.Method;
import java.nio.channels.FileChannel;

/**
 * J2ObjC-specific bridge class so jre_core and jre_channels can remain separate.
 */
class FileChannelOpener {

  // Used by FileInputStream.getChannel() and RandomAccessFile.getChannel()
  public static FileChannel open(
      FileDescriptor fd, String path, boolean readable, boolean writable, Object parent) {
    try {
      Class<?> cls = Class.forName("sun.nio.ch.FileChannelImpl");
      Method m =
          cls.getDeclaredMethod(
              "open", FileDescriptor.class, String.class, Boolean.TYPE, Boolean.TYPE, Object.class);
      return (FileChannel) m.invoke(null, fd, path, readable, writable, parent);
    } catch (ClassNotFoundException e) {
      throw new LibraryNotLinkedError("Channel support", "jre_channels", "SunNioChFileChannelImpl");
    } catch (Exception e) {
      throw new AssertionError("failed opening file channel", e);
    }
  }

    // Used by FileOutputStream.getChannel
    public static FileChannel open(FileDescriptor fd, String path,
                                   boolean readable, boolean writable,
                                   boolean append, Object parent)
    {
    try {
      Class<?> cls = Class.forName("sun.nio.ch.FileChannelImpl");
      Method m =
          cls.getDeclaredMethod(
              "open",
              FileDescriptor.class,
              String.class,
              Boolean.TYPE,
              Boolean.TYPE,
              Boolean.TYPE,
              Object.class);
      return (FileChannel) m.invoke(null, fd, path, readable, writable, append, parent);
    } catch (ClassNotFoundException e) {
      throw new LibraryNotLinkedError("Channel support", "jre_channels", "SunNioChFileChannelImpl");
    } catch (Exception e) {
      throw new AssertionError("failed opening file channel", e);
    }
  }
}
